import type { UserState } from '@/api/user'
import { clearToken, setToken } from '@/utils/auth'
import { defineStore } from 'pinia'

import {
  getUserInfo,
  logout as userLogout,
} from '@/api/user'

// 从login.ts导入登录、注册和登出函数
import {
  resetPassword,
  sendVerificationCode,
  login as userLogin,
  register as userRegister,
} from '@/api/login'

const InitUserInfo = {
  uid: 0,
  nickname: '',
  headimg: '',
  member:'',
  recomcode:"",
  minlevel: 0,
  vipImg:''
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserState>({ ...InitUserInfo })

  // Set user's information
  const setInfo = (partial: Partial<UserState>) => {
    userInfo.value = { ...partial }
  }

  const login = async (loginForm: {
    account?: string
    areaCode?: string
    loginPassword?: string
    device?: string
    username?: string
    password?: string
    code?: string
  }) => {
    try {
      const response = await userLogin(loginForm)
      if (response.data?.token) {
        setToken(response.data.token)
      }
      return response
    }
    catch (error) {
      clearToken()
      throw error
    }
  }

  const info = async () => {
    try {
      const { data } = await getUserInfo()
      setInfo(data)
    }
    catch (error) {
      clearToken()
      throw error
    }
  }

  const logout = async () => {
    try {
      await userLogout()
    }
    finally {
      clearToken()
      setInfo({ ...InitUserInfo })
    }
  }

  const getCode = async (email: string) => {
    try {
      const data = await sendVerificationCode(email)
      return data
    }
    catch {}
  }

  const reset = async (resetForm: {
    email: string
    code: string
    newPassword: string
    confirmPassword: string
  }) => {
    try {
      const data = await resetPassword(resetForm)
      return data
    }
    catch {}
  }

  const register = async (registerForm: {
    tel: string
    areaCode: string
    loginPassword: string
    parent: string
  }) => {
    try {
      const data = await userRegister(registerForm)
      return data
    }
    catch {}
  }

  return {
    userInfo,
    info,
    login,
    logout,
    getCode,
    reset,
    register,
  }
}, {
  persist: true,
})

export default useUserStore
